package com.tanhua.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.domain.db.Admin;
import com.tanhua.domain.web.ResultInfo;
import com.tanhua.dubbo.api.AdminApi;
import com.tanhua.utils.JwtUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
public class AdminService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${tanhua.secret}")
    private String secret;

    @Reference
    private AdminApi adminApi;

    public ResultInfo login(Admin admin) {
        boolean b = false;
        Admin aName = adminApi.findByAdminName(admin.getAdminName());
        if (aName != null) {
            if (aName.getPassword() != null && aName.getPassword().equals(admin.getPassword())) {
                b = true;
            } else {
            }
        }
        String tokenKey = null;
        if (b) {
            //生成token
            String token = JwtUtils.createToken(admin.getId(), "10086", secret);
            //把用户对象存储到redis中
            String adminJson = JSON.toJSONString(admin);
            tokenKey = "TOKEN_KEY_" + token;
            redisTemplate.opsForValue().set(tokenKey, adminJson, Duration.ofHours(4));
        } else {
            return new ResultInfo(false, "登陆失败");
        }
        return new ResultInfo(true, "登陆成功", tokenKey);
    }


    public void logout(String token) {
        String tokenKey = "TOKEN_KEY_" + token;

        redisTemplate.delete(tokenKey);
    }


    public Admin findUserByToken(String token) {

        String json = redisTemplate.opsForValue().get(token);
        Admin admin = JSON.parseObject(json, Admin.class);

        return admin;
    }
}
